//
//  MineViewController.m
//  MovieDate
//
//  Created by ann on 16/3/11.
//  Copyright © 2016年 MovieDate. All rights reserved.
//

#import "MineViewController.h"
#import "MineTableViewCell.h"
#import "MyWalletViewController.h"
#import "UserSettingViewController.h"
#import "EditDataViewController.h"

@interface MineViewController ()<UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate,UITextViewDelegate>
{
//    //输入框
//    UITextView *_textEditor;
    
    //下拉菜单
    UIActionSheet *myActionSheet;
    
    //图片2进制路径
    NSString* filePath;


}
@property (weak, nonatomic) IBOutlet UITableView *minefirstPageTableView;

@property (weak, nonatomic) IBOutlet UIImageView *mineBGimageView;

@property (strong, nonatomic) IBOutlet UIView *pViewHeader;


@end

@implementation MineViewController

-(void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = NO;
    User *user = [User defaultUser];
    self.userZambiaLB.text =  [NSString stringWithFormat:@"%@", user.zambia];
    
    [self request];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self initView];
    // Do any additional setup after loading the view.
}

- (void)request
{
    [TDNetwork requsetUseMessagePostUrl:useGetMessageIP complete:^(BOOL succeed, NSString *ret, NSDictionary *dictionary) {
        if (succeed) {
            
            NSDictionary *dic = [dictionary valueForKey:@"res"];
            NSLog(@"用户信息是：%@",dic);
            User *user = [User defaultUser];
            if (dic) {
                user.uid = [dic valueForKey:@"uid"];
                user.headImage = [dic valueForKey:@"headImage"];
                user.nickName = [dic valueForKey:@"nickName"];
                user.userAge = [dic valueForKey:@"userAge"];
                user.userSex = [dic valueForKey:@"userSex"];
                user.zambia = [dic valueForKey:@"zambia"];
                user.faceScore = [dic valueForKey:@"faceScore"];
                user.fans  = [dic valueForKey:@"fans"];
                user.movieLabel = [dic valueForKey:@"movieLabel"];
                user.commentCount = [dic valueForKey:@"commentCount"];
                user.commentStart = [dic valueForKey:@"commentStart"];
                user.commentTotalScore = [dic valueForKey:@"commentTotalScore"];
                user.phone = [dic valueForKey:@"phone"];
                user.pwd =  [dic valueForKey:@"pwd"];
                user.beReprotedCount = [dic valueForKey:@"beReportedCount"];
                user.appointmentCount = [dic valueForKey:@"appointmentCount"];
                user.breakCount = [dic valueForKey:@"breakCount"];
                user.signature = [dic valueForKey:@"signature"];
                
                NSString *labels =  [dic valueForKey:@"labels"];
                @try {
                    [labels stringByReplacingOccurrencesOfString:@"\\U" withString:@"!u"];
                    [labels stringByReplacingOccurrencesOfString:@"\\" withString:@""];
                    [labels stringByReplacingOccurrencesOfString:@"!u" withString:@"\\u"];
                    NSString *labels2 = [labels stringByReplacingOccurrencesOfString:@"\'" withString:@"\""];
                    [user.labels removeAllObjects];
                    NSArray *arr =  [self arrWithJsonString:labels2];
                    for (NSDictionary *dic in arr)
                    {
                        MovieLabelModel *movieLbM = [[MovieLabelModel alloc]init];
                        movieLbM.name = [dic valueForKey:@"name"];
                        movieLbM.type = [NSString stringWithFormat:@"%@",[dic valueForKey:@"type"]];
                        movieLbM.uuid = [NSString stringWithFormat:@"%@",[dic valueForKey:@"uuid"]];
                        [user.labels addObject:movieLbM];
                    }
                } @catch (NSException *exception) {
                } @finally {
                }
            }
        } else {
        }
    }];
}

- (NSMutableArray *)arrWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSMutableArray *arr = [NSJSONSerialization JSONObjectWithData:jsonData
                                                          options:NSJSONReadingMutableContainers
                                                            error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return arr;
}


-(void)initView
{
    [self.pViewHeader setFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.width + 48)];
    self.pTableView.tableHeaderView = self.pViewHeader;
    
    self.minefirstPageTableView .delegate = self;
    self.minefirstPageTableView.dataSource = self;
    self.mineBGimageView.userInteractionEnabled = NO;
    UIView *view = [[UIView alloc]init];

    [self.minefirstPageTableView setTableFooterView:view];
    self.navigationController.navigationBar.barTintColor = [UIColor grayColor];
    User *user = [User defaultUser];
    
    self.userDetailEditBTN.layer.masksToBounds = YES;
    self.userDetailEditBTN.layer.cornerRadius = 30;
    self.userFaceScoreLB.text =  [NSString stringWithFormat:@"%@", user.faceScore];
    
    self.UserFansLB.text =  [NSString stringWithFormat:@"%@", user.fans];
    [self.userBackgroundImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", IP, user.headImage]]];
    [self.userPicImageView  sd_setBackgroundImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", IP, user.headImage]] forState:(UIControlStateNormal)];
    [self.userPicImageView sd_setBackgroundImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", IP, user.headImage]] forState:(UIControlStateHighlighted)];
    
    self.userPicImageView.layer.borderWidth = 4;
    self.userPicImageView.layer.borderColor = [[UIColor colorWithRed:192.0/255 green:192.0/255 blue:192.0/255 alpha:1] CGColor];
    self.userPicImageView.layer.masksToBounds = YES;
    self.userPicImageView.layer.cornerRadius = 71;
    
    UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.width)];
    toolbar.barStyle = UIBarStyleBlackTranslucent;
    [toolbar setTranslucent:YES];
    [toolbar setAlpha:0.95f];
    [self.pViewHeader insertSubview:toolbar aboveSubview:self.mineBGimageView];
}
- (IBAction)onPhoneAlbum:(id)sender {
    //在这里呼出下方菜单按钮项
    myActionSheet = [[UIActionSheet alloc]
                     initWithTitle:@"请上传您的真实照片作为头像"
                     delegate:self
                     cancelButtonTitle:@"取消"
                     destructiveButtonTitle:nil
                     otherButtonTitles: @"打开照相机", @"从手机相册获取",nil];
    
    [myActionSheet showInView:self.view];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    //呼出的菜单按钮点击后的响应
    if (buttonIndex == myActionSheet.cancelButtonIndex)
    {
        NSLog(@"取消");
    }
    
    switch (buttonIndex)
    {
     
        case 0:  //打开照相机拍照
            [self takePhoto];
            break;
            
        case 1:  //打开本地相册
            [self LocalPhoto];
            break;
    }
}

//开始拍照
-(void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        [self presentModalViewController:picker animated:YES];
    }else{
        NSLog(@"模拟其中无法打开照相机,请在真机中使用");
    }
}

//打开本地相册
-(void)LocalPhoto
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    [self presentModalViewController:picker animated:YES];

}
//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
        NSData *data;
            data = UIImageJPEGRepresentation(image, 0.5);
        
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        
        //文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data attributes:nil];
        
        //得到选择后沙盒中图片的完整路径
        filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath, @"/image.png"];
        //关闭相册界面
        [picker dismissModalViewControllerAnimated:YES];
        //创建一个选择后图片的小图标放在下方
        //类似微薄选择图后的效果
        self.userBackgroundImageView.image = image;
        UIBlurEffect *blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
        
        UIVisualEffectView *effectview = [[UIVisualEffectView alloc] initWithEffect:blur];
        effectview.alpha = 0.5;
        effectview.frame =self.userBackgroundImageView.frame;
        [self.userBackgroundImageView addSubview:effectview];
        [self.userPicImageView setBackgroundImage:image forState:(UIControlStateNormal)];
        [self.userPicImageView setBackgroundImage:image forState:(UIControlStateHighlighted)];
        NSString *encodedImageStr = [data base64Encoding];
        User *user = [User defaultUser];
        [SVProgressHUD show];
        [TDNetwork uploadingUserPicImagePostUrl:uploadingPicImageIP
                                   imgName: [NSString stringWithFormat:@"%@.png",user.nickName]
                                   imgData:encodedImageStr
                                     title:@"图片"
                                      type:@"png"
                                  complete:^(BOOL succeed, NSString *ret, NSDictionary *dictionary) {
                       if (succeed)
                       {
                            switch ([ret intValue])
                           {
                                case 1:
                                 user.picFid = [NSString stringWithFormat:@"%@", [[dictionary valueForKey:@"res"] valueForKey:@"fid"]];
                                [TDNetwork settingUserHeadImagePostUrl:settingHeadImageIP fid:[user.picFid integerValue]complete:^(BOOL succeed, NSString *ret, NSDictionary *dictionary) {
                                    if (succeed) {
                                        if ([ret intValue]) {
                                               [SVProgressHUD showSuccessWithStatus:@"头像设置成功"];
                                        }
                                    } else {
                                        [SVProgressHUD showErrorWithStatus:@"头像设置失败"];
                                    }
                                }];
                                    [SVProgressHUD dismiss];
                                    break;
                                case 2:
                                    [SVProgressHUD showErrorWithStatus:@"格式不对"];
                             
                                    break;
                                case 3:
                                    [SVProgressHUD showErrorWithStatus:@"大小超限"];
                                 
                                    break;
                                default:
                                    [SVProgressHUD showErrorWithStatus:@"未知错误"];
                              
                                    break;
                            }
                    } else {
                        [SVProgressHUD showErrorWithStatus:@"网络请求错误"];
                    }
                }];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissModalViewControllerAnimated:YES];
}

- (IBAction)clickPushOnEditData:(id)sender {
    [self performSegueWithIdentifier:@"idfEditUserInfoVC" sender:nil];
//        EditDataViewController *editDataVC = [[EditDataViewController alloc]init];
//        [self.navigationController pushViewController:editDataVC animated:YES];
}


#pragma mark  UITableViewDataSource,UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  static NSString *identifier = @"mineCell1";
    MineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"MineTableViewCell" owner:self options:nil] firstObject];
        }
    switch (indexPath.row) {
        case 0:
            cell.tittleLb.text = @"我的电影票";
            cell.introduceLB.text = @"领取、查看电影票";
            cell.picImageView.image = [UIImage imageNamed:@"userCenter_ticket"];
            break;
            
        case 1:
             cell.tittleLb.text = @"设置";
             cell.introduceLB.text = @"通知、账户和更多";
             cell.picImageView.image = [UIImage imageNamed:@"userCenter_set"];
            break;
            
        case 2:
             cell.tittleLb.text = @"关于约人看电影";
             cell.introduceLB.text = @"常见问题及玩法攻略";
             cell.picImageView.image = [UIImage imageNamed:@"userCenter_about"];
            break;
            
        default:
            break;
}
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    [self selectRowTouchAction:indexPath];
}

-(void)selectRowTouchAction:(NSIndexPath *)indexPath {
    switch (indexPath.row) {
        case 0:
            [self performSegueWithIdentifier:@"idfMyTicketVC" sender:nil];
            break;
            
        case 1:
            [self pushSetting];
            break;
            
        case 2:
            [self performSegueWithIdentifier:@"idfAboutYanYanViewController" sender:nil];
            break;
            
        default:
            NSLog(@"暂时未开通");
            break;
    }
}

- (void)pushMyWallet {
    MyWalletViewController *myWalletVC = [[MyWalletViewController alloc]init];
    [self.navigationController pushViewController:myWalletVC animated:YES];
}

- (void)pushSetting {
    UserSettingViewController *setVC = [[UserSettingViewController alloc]init];
    [self.navigationController pushViewController:setVC animated:YES];
}

- (void)pushMineEditData{

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
